package com.ebeijia.controller;

import javax.annotation.Resource;

import com.ebeijia.context.RequestResponseContext;
import com.ebeijia.context.UserContext;
import com.ebeijia.mybatis.pojo.UserManage;
import com.ebeijia.service.admin.UserManageService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ebeijia.web.ResponseMessage;

/**
 * Created by YPJ on 2016/5/12.
 */
@Controller
public class LoginController extends BaseController {

    @Resource
    private UserManageService userManageService;

    @RequestMapping("/doLogin.htm")
    public ModelAndView login() {
        ModelAndView modelAndView = new ModelAndView("/login");
        String backUrl = RequestResponseContext.getParam("backUrl");
        if (StringUtils.isBlank(backUrl)) {
            modelAndView.addObject("backUrl", backUrl);
        }

        return modelAndView;
    }

    @RequestMapping("/doLogin.json")
    @ResponseBody
    public ResponseMessage loginJson(String account, String pwd) {

        UserManage userManage = new UserManage();
        userManage.setAccount(account);
        userManage.setPwd(pwd);
        if (userManageService.selectByAccount(userManage) != null) {
            UserContext userContext = new UserContext();
            userContext.setAccount(account);
            refreshUserContext(RequestResponseContext.getRequest(), userContext);
            String backUrl = RequestResponseContext.getParam("backUrl");
            return ResponseMessage.success(backUrl);
        } else {
            return ResponseMessage.error("用户名或者密码错误");
        }

    }

    @RequestMapping("exit.htm")
    public String exit() {
        RequestResponseContext.getRequest().getSession().removeAttribute("userManage");
        return "redirect:/";
    }

}
